package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.BalanceAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.BalanceBean;
import com.laiyima.zhongjiang.linghuilv.demo.bean.BalanceChildBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wangchenlong.datescroller.widget.DateScrollerDialog;
import org.wangchenlong.datescroller.widget.data.Type;
import org.wangchenlong.datescroller.widget.listener.OnDateSetListener;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class BanlanceDetActivity extends SwipeBackActivity implements ListViewPlus.ListViewPlusListener {
    private String TAG="BanlanceDetActivity";
    private int bdCode;

    private LinearLayout balancedet_back,no_balancedet;
    private int page_count, count, page_index;
    private String time;
    private TextView balance_find_time;

     private ListViewPlus mListView;
    private BalanceAdapter newTranAdapter;
    List<BalanceBean> NewTranBeanlist;

    @Override
    public void onRefresh() {
        NewTranBeanlist.clear();
        intView();
        newTranAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);

    }

    @Override
    public void onLoadMore() {
        if (page_index < page_count) {
            loadData(ListViewPlus.LOAD);
        } else {
            Toast.makeText(getBaseContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:

                    //intView();
                    onLoadComplete();
                    Toast.makeText(getBaseContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    loadMode(page_index, time);
                    break;
            }

        }

        ;
    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }
    private void loadMode(int page_index, String time) {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/withdraw_d");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("time", time);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    bdCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                     String list = jData.optString("list", null);
                    JSONObject lisobject = new JSONObject(list);
                    Iterator<String> iterator = lisobject.keys();
                    while (iterator.hasNext()) {
                        BalanceBean tran = new BalanceBean();
                        String key = iterator.next();//获取key日期
                        String oneday = lisobject.optString(key, null);
                        Log.e(TAG, key + oneday);
                        JSONObject onedayobject = new JSONObject(oneday);
                        String day_money = onedayobject.optString("money", "");//获取每日总数
                        JSONArray array = onedayobject.getJSONArray("month");
                        tran.setKey(key);
                        tran.setMoney(day_money);
                        List<BalanceChildBean> TransactiondetailsBeanList = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            BalanceChildBean itemBean = new BalanceChildBean();
                            JSONObject jsonObject1 = (JSONObject) array.get(i);
                            itemBean.setMoney(jsonObject1.optString("money"));
                            itemBean.setFee(jsonObject1.optString("fee"));
                            itemBean.setCreate_time(jsonObject1.optString("create_time"));
                            itemBean.setId(jsonObject1.optString("id"));
                            itemBean.setUid(jsonObject1.optString("uid"));
                            itemBean.setState(jsonObject1.optString("state"));
                            itemBean.setDesc(jsonObject1.optString("desc"));
                            TransactiondetailsBeanList.add(itemBean);
                        }
                        tran.setItems(TransactiondetailsBeanList);
                        NewTranBeanlist.add(tran);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (bdCode == 200) {
                    newTranAdapter = new BalanceAdapter( BanlanceDetActivity.this, NewTranBeanlist);
                    mListView.setAdapter(newTranAdapter);
                }

                if (bdCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                onLoadComplete();
            }
        });

    }















    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_banlance_det);
        balancedet_back= (LinearLayout) findViewById(R.id.balancedet_back);
        balancedet_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        no_balancedet= (LinearLayout) findViewById(R.id.no_balancedet);
        balance_find_time= (TextView) findViewById(R.id.balance_find_time);
        balance_find_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shoewtime();
            }
        });


        mListView = (ListViewPlus) findViewById(R.id.balance_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        NewTranBeanlist=new ArrayList<>();
        intView();
        setStatusBar();
    }
    private void intView(){
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/withdraw_d");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    bdCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    count = jData.optInt("count", 0);
                    page_count = jData.optInt("page_count", 0);
                    page_index = jData.optInt("page_index", 0);
                    Log.e(TAG, "count" + count+"page_count:"+page_count+"page_index"+page_index);
                    String list = jData.optString("list", null);
                    JSONObject lisobject = new JSONObject(list);
                    Iterator<String> iterator = lisobject.keys();
                    while (iterator.hasNext()) {
                        BalanceBean tran = new BalanceBean();
                        String key = iterator.next();//获取key日期
                        String oneday = lisobject.optString(key, null);
                        Log.e(TAG, key + oneday);
                        JSONObject onedayobject = new JSONObject(oneday);
                        String day_money = onedayobject.optString("money", "");//获取每日总数
                        JSONArray array = onedayobject.getJSONArray("month");
                        tran.setKey(key);
                        tran.setMoney(day_money);
                        List<BalanceChildBean> TransactiondetailsBeanList = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            BalanceChildBean itemBean = new BalanceChildBean();
                            JSONObject jsonObject1 = (JSONObject) array.get(i);
                            itemBean.setMoney(jsonObject1.optString("money"));
                            itemBean.setFee(jsonObject1.optString("fee"));
                            itemBean.setCreate_time(jsonObject1.optString("create_time"));
                            itemBean.setId(jsonObject1.optString("id"));
                            itemBean.setUid(jsonObject1.optString("uid"));
                            itemBean.setState(jsonObject1.optString("state"));
                            itemBean.setDesc(jsonObject1.optString("desc"));
                            TransactiondetailsBeanList.add(itemBean);
                        }
                        tran.setItems(TransactiondetailsBeanList);
                        NewTranBeanlist.add(tran);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (bdCode == 200) {
                    newTranAdapter = new BalanceAdapter( BanlanceDetActivity.this, NewTranBeanlist);
                    mListView.setAdapter(newTranAdapter);
                }

                if (bdCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (NewTranBeanlist.size() == 0) {
                    no_balancedet.setVisibility(View.VISIBLE);
                } else {
                    no_balancedet.setVisibility(View.GONE);
                }
            }
        });

    }



    private void shoewtime() {
        DateScrollerDialog dialog = new DateScrollerDialog.Builder()
                .setType(Type.YEAR_MONTH)
                .setMinMilliseconds(System.currentTimeMillis() - HUNDRED_YEARS)
                .setMaxMilliseconds(System.currentTimeMillis())
                .setCurMilliseconds(mLastTime)
                .setCallback(mOnDateSetListener)
                .build();


        if (dialog != null) {
            if (!dialog.isAdded()) {
                dialog.show(getFragmentManager(), "year_month_day");
            }
        }
    }

    private static final long HUNDRED_YEARS = 100L * 365 * 1000 * 60 * 60 * 24L;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM", Locale.ENGLISH);
    private long mLastTime = System.currentTimeMillis();
    private OnDateSetListener mOnDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DateScrollerDialog timePickerView, long milliseconds) {
            mLastTime = milliseconds;
            time = getDateToString(milliseconds);
             findView(time);
        }
    };

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

    private void findView(String time) {
        if (NewTranBeanlist != null) {
            NewTranBeanlist.clear();
        }
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/withdraw_d");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("time", time);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    bdCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    count = jData.optInt("count", 0);
                    page_count = jData.optInt("page_count", 0);
                    page_index = jData.optInt("page_index", 0);
                    Log.e(TAG, "count" + count+"page_count:"+page_count+"page_index"+page_index);
                    String list = jData.optString("list", null);
                    JSONObject lisobject = new JSONObject(list);
                    Iterator<String> iterator = lisobject.keys();
                    while (iterator.hasNext()) {
                        BalanceBean tran = new BalanceBean();
                        String key = iterator.next();//获取key日期
                        String oneday = lisobject.optString(key, null);
                        Log.e(TAG, key + oneday);
                        JSONObject onedayobject = new JSONObject(oneday);
                        String day_money = onedayobject.optString("money", "");//获取每日总数
                        JSONArray array = onedayobject.getJSONArray("month");
                        tran.setKey(key);
                        tran.setMoney(day_money);
                        List<BalanceChildBean> TransactiondetailsBeanList = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            BalanceChildBean itemBean = new BalanceChildBean();
                            JSONObject jsonObject1 = (JSONObject) array.get(i);
                            itemBean.setMoney(jsonObject1.optString("money"));
                            itemBean.setFee(jsonObject1.optString("fee"));
                            itemBean.setCreate_time(jsonObject1.optString("create_time"));
                            itemBean.setId(jsonObject1.optString("id"));
                            itemBean.setUid(jsonObject1.optString("uid"));
                            itemBean.setState(jsonObject1.optString("state"));
                            itemBean.setDesc(jsonObject1.optString("desc"));
                            TransactiondetailsBeanList.add(itemBean);
                        }
                        tran.setItems(TransactiondetailsBeanList);
                        NewTranBeanlist.add(tran);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (bdCode == 200) {
                    newTranAdapter = new BalanceAdapter( BanlanceDetActivity.this, NewTranBeanlist);
                    mListView.setAdapter(newTranAdapter);
                }

                if (bdCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (NewTranBeanlist.size() == 0) {
                    no_balancedet.setVisibility(View.VISIBLE);
                } else {
                    no_balancedet.setVisibility(View.GONE);
                }
            }
        });

    }

}
